<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="成果名称" prop="title">
        <el-input v-model="queryParams.searchWord" placeholder="请输入成果名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="行业领域" prop="industrySector">
        <el-select v-model="queryParams.industrySector" placeholder="请选择行业领域">
          <el-option v-for="item in industrySectorList" :key="item.label" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择审核状态">
          <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['kjy:achievement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate2"
          v-hasPermi="['kjy:achievement:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['kjy:achievement:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="achievementList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand" label="更多">
        <template slot-scope="props">
          <el-form label-position="right" label-width="120px" inline class="achievement-table-expand">
            <el-form-item label="行业领域">
              <el-tag v-for="item in props.row.industrySector" :key="item">
                {{ item }}
              </el-tag>
            </el-form-item>
            <el-form-item label="所在地">
              <span>
                {{ props.row.location && props.row.location.join(" / ") }}
              </span>
            </el-form-item>
            <el-form-item label="关联组织">
              <span>{{ props.row.associatedOrganizations }}</span>
            </el-form-item>
            <el-form-item v-if="props.row.patentsType !== '非专利'" label="专利号">
              <span>{{ props.row.patentNumber }}</span>
            </el-form-item>
            <el-form-item v-if="props.row.patentsType !== '非专利'" label="专利授权时间">
              <span>
                {{ parseTime(props.row.authorizationTime, "{y}-{m}-{d}") }}
              </span>
            </el-form-item>
            <el-form-item v-if="props.row.state === -1" label="审核不通过原因">
              <span>
                {{ props.row.failedReason }}
              </span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="成果名称" align="center" prop="title" />
      <el-table-column label="成果形式" align="center" prop="patentsType">
      </el-table-column>
      <el-table-column label="成熟度" align="center" prop="maturity">
      </el-table-column>
      <el-table-column label="合作意向" align="center" prop="cooperationIntention">
      </el-table-column>
      <el-table-column label="内容" align="center" prop="content">
        <template slot-scope="scope">
          <el-popover popper-class="my-popper" trigger="click" placement="top">
            <div v-html="scope.row.content"></div>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" class="pointer">点击查看</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="发布人名称" align="center" prop="authorName" />
      <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.state === 0" type="warning">审核中</el-tag>
          <el-tag v-if="scope.row.state === -1" type="danger">未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kjy:achievement:edit']">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['kjy:achievement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
      @pagination="getList" />

    <!-- 添加或修改科技成果管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="审核状态" prop="state">
          <el-radio v-model="form.state" :label="1">通过</el-radio>
          <el-radio v-model="form.state" :label="-1">不通过</el-radio>
        </el-form-item>
        <el-form-item v-if="form.state === -1" label="审核不通过原因" prop="failedReason">
          <el-input v-model="form.failedReason" placeholder="请输入审核不通过原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改科技成果管理对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="成果名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入成果名称"></el-input>
        </el-form-item>
        <el-form-item class="industry" label="行业领域" prop="industrySector">
          <el-select v-model="form.industrySector" multiple clearable placeholder="请选择">
            <el-option v-for="option in industrySectorList" :key="option.label" :label="option.label"
              :value="option.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="location" label="所在地" prop="location">
          <el-cascader v-model="form.location" :props="cityProps" :options="cityData"
            placeholder="请选择所在地"></el-cascader>
        </el-form-item>
        <el-form-item label="专利情况" prop="patentsType">
          <el-radio-group v-model="form.patentsType">
            <el-radio label="非专利">非专利</el-radio>
            <el-radio label="发明专利">发明专利</el-radio>
            <el-radio label="实用新型">实用新型</el-radio>
            <el-radio label="外观设计">外观设计</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.patentsType && form.patentsType !== '非专利'" class="patent-no" label="专利号"
          prop="patentNumber">
          <el-input v-model="form.patentNumber" placeholder="请输入专利号"></el-input>
        </el-form-item>
        <el-form-item v-if="form.patentsType && form.patentsType !== '非专利'" class="patent-date" label="专利授权日期"
          prop="authorizationTime">
          <el-date-picker v-model="form.authorizationTime" value-format="yyyy-MM-dd" type="date" placeholder="请选择专利授权日期"
            :disabled-date="disabledAfterDate" />
        </el-form-item>
        <el-form-item class="associated-organization" label="关联组织" prop="associatedOrganizations">
          <el-input v-model="form.associatedOrganizations" placeholder="请输入关联组织"></el-input>
        </el-form-item>
        <el-form-item label="成熟度" prop="maturity">
          <el-radio-group v-model="form.maturity">
            <el-radio label="正在研发">正在研发</el-radio>
            <el-radio label="已有样品">已有样品</el-radio>
            <el-radio label="可以量产">可以量产</el-radio>
            <!-- 其他选项 -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合作意向" prop="cooperationIntention">
          <el-radio-group v-model="form.cooperationIntention">
            <el-radio label="技术转让">技术转让</el-radio>
            <el-radio label="技术授权">技术授权</el-radio>
            <el-radio label="合作开发">合作开发</el-radio>
            <!-- 其他选项 -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成果简介" prop="content">
          <div style="border: 1px solid #ccc">
            <web-editor style="height: 250px; overflow-y: hidden" v-model="form.content" />
          </div>
        </el-form-item>
        <el-form-item label="年份" prop="contractYear">
          <el-input v-model="form.contractYear" placeholder="请输入合同年份"></el-input>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合同编号"></el-input>
        </el-form-item>
        <el-form-item label="技术交易额（元）" prop="contractVolume">
          <el-input v-model="form.contractVolume" placeholder="请输入技术交易额（元）"></el-input>
        </el-form-item>
        <el-form-item label="买方名称" prop="contractBuyer">
          <el-input v-model="form.contractBuyer" placeholder="请输入买方名称"></el-input>
        </el-form-item>
        <el-form-item class="contractCity" label="落地城市" prop="contractCity">
          <el-cascader v-model="form.contractCity" :props="cityProps" :options="cityData"
            placeholder="请选择落地城市"></el-cascader>
        </el-form-item>
        <el-form-item label="上传附件" prop="attach">
          <el-upload
            class="upload-demo"
            action="/prod-api/file/upload"
            :on-remove="handleRemove"
            :on-change="handleChange"
            multiple
            :limit="10"
            :on-exceed="handleExceed"
            :file-list="uploadedFileList"
            :headers="{ Authorization: getToken() }"
            :on-preview="handlePreview"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAchievement,
  getAchievement,
  delAchievement,
  addAchievement,
  updateAchievement,
} from "@/api/system/achievement";
import { industrySectorList } from "@/data/industrySectorList";
import cityData from '@/data/cityData.json';
import { getToken } from "@/utils/auth";
import { uploadFile } from "@/api/system/file.js";
export default {
  name: "Achievement",
  data() {
    // 专利号校验规则
    const validatePatentNumber = (rule, value, callback) => {
      if (this.form.patentsType && this.form.patentsType !== '非专利') {
        if (!value) {
          callback(new Error('专利号不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    // 专利授权日期校验规则
    const validateAuthorizationTime = (rule, value, callback) => {
      if (this.form.patentsType && this.form.patentsType !== '非专利') {
        if (!value) {
          callback(new Error('专利授权日期不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    // 成果简介校验规则
    const validateContent = (rule, value, callback) => {
      const strippedContent = value ? value.replace(/<[^>]+>/g, '').trim() : '';
      if (!value || strippedContent.length === 0) {
        callback(new Error('成果简介不能为空'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科技成果管理表格数据
      achievementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        industrySector: null,
        searchWord: null,
        state: null,
      },
      // 表单参数
      form: {
        industrySector: [],
        location: [],
        budget: 1000,
        title: '',
        // 内容 HTML
        content: '',
        patentsType: '',
        patentNumber: '',
        authorizationTime: '',
        associatedOrganizations: '',
        maturity: '',
        cooperationIntention: '',
        contractYear: '',
        contractCode: '',
        contractVolume: '',
        contractType: '',
        contractBuyer: '',
        contractCity: ''
      },
      cityProps: {
        value: 'name', // 指定选项的 值 为选项对象的某个属性值
        label: 'name', // 指定选项 标签 为选项对象的某个属性值
        children: 'children', //指定选项的 子选项 为选项对象的某个属性值
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: '成果名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '成果名称长度不能超过100个字符', trigger: 'blur' }
        ],
        industrySector: [
          { required: true, message: '行业领域不能为空', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '所在地不能为空', trigger: 'change' }
        ],
        patentsType: [
          { required: true, message: '专利情况不能为空', trigger: 'change' }
        ],
        patentNumber: [
          { required: true,  validator: validatePatentNumber, trigger: 'blur' }
        ],
        authorizationTime: [
          { required: true, validator: validateAuthorizationTime, trigger: 'change' }
        ],
        maturity: [
          { required: true, message: '成熟度不能为空', trigger: 'change' }
        ],
        cooperationIntention: [
          { required: true, message: '合作意向不能为空', trigger: 'change' }
        ],
        content: [
          { required: true, validator: validateContent, trigger: 'blur' }
        ],
        state: [
          { required: true, message: '审核状态不能为空', trigger: 'change' }
        ],
        failedReason: [
          { required: true, message: '审核不通过原因不能为空', trigger: 'blur' }
        ]
      },
      stateList: [
        { value: null, label: "全部" },
        { value: 0, label: "审核中" },
        { value: 1, label: "已通过" },
        { value: -1, label: "未通过" },
      ],
      industrySectorList: industrySectorList,
      cityData: cityData,
      uploadedFileList: [],
      fileList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询科技成果管理列表 */
    getList() {
      this.loading = true;
      listAchievement(this.queryParams).then((response) => {
        this.achievementList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        industrySector: null,
        patentsType: null,
        maturity: null,
        cooperationIntention: null,
        associatedOrganizations: null,
        evaluate: null,
        content: null,
        title: null,
        author: null,
        authorName: null,
        authorizationTime: null,
        patentNumber: null,
        releaseTime: null,
        createTime: null,
        location: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        state: null,
        failedReason: null,
        contractYear: null,
        contractCode: null,
        contractVolume: null,
        contractType: null,
        contractBuyer: null,
        contractCity: null,
        files: null,
      };
      this.resetForm("form");
      this.fileList = [];
      this.uploadedFileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.searchWord = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open2 = true;
      this.title = "添加科技成果";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAchievement(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "审核科技成果";
      });
    },
    handleUpdate2(row) {
      this.reset();
      const id = row.id || this.ids;
      getAchievement(id).then((response) => {
        this.form = response.data;
        this.uploadedFileList = response.data.files ?? [];
        this.open2 = true;
        this.title = "修改科技成果";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAchievement(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAchievement(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitForm2() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (this.form.authorizationTime !== null && !this.form.authorizationTime.includes(' 00:00:00')) {
            this.form.authorizationTime += ' 00:00:00';
          }
          this.form.files = this.uploadedFileList;
          for (const file of this.fileList) {
            const formData = new FormData();
            formData.append("file", file);
            const res = await uploadFile(formData);
            if (res.code === 200) {
              const { name, url } = res.data;
              this.form.files.push({
                name,
                url,
              });
            }
          }

          if (this.form.id != null) {
            updateAchievement(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open2 = false;
              this.getList();
            });
          } else {
            addAchievement(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open2 = false;
              this.getList();
            });
          }
        }
      });
    },
    disabledAfterDate(date) {
      const today = new Date();
      today.setDate(today.getDate());
      return date > today;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除所选的成果？")
        .then(function () {
          return delAchievement(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download(
    //     "kjy/achievement/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `achievement_${new Date().getTime()}.xlsx`
    //   );
    // },
    getToken() {
      return getToken();
    },
     // 文件上传
     handleChange(file, fileList) {
      this.fileList.push(file.raw);
    },
    handleRemove(file, fileList) {
      let index = this.fileList.indexOf(file.raw);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      // 不止要删除fileRawList，还要删除已存在的文件列表
      let exitsIndex = this.uploadedFileList.findIndex(
        (item) => item.uid === file.uid
      );
      if (exitsIndex !== -1) {
        this.uploadedFileList.splice(exitsIndex, 1);
      }
    },
    handlePreview(file) {
      if (file.url) {
        // 只能预览已上传的文件
        const link = document.createElement("a");
        document.body.appendChild(link);
        link.style.display = "none"; // 隐藏起来
        link.href = file.url;
        link.target = "_blank"; // 在新窗口或标签页中打开链接
        link.click();
        document.body.removeChild(link);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
  },
};
</script>
<style>
/* 表格展开样式 */
.pointer {
  cursor: pointer;
}
.achievement-table-expand {
  font-size: 0;
  padding: 0 10%;
}

.achievement-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.achievement-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
